const { Transform } = require("stream");
const fs = require("fs");
const _ = require("lodash");
const utils = require('../../utils');

module.exports = function (file, widths = {}) {
  const stream = new Transform({ objectMode: true });
  const fd = fs.openSync(file, 'w');
  let hasTitle = false;
  let keys;

  stream._transform = function (chunk, encoding, callback) {
    utils.debug('textWriter [chunk]:', chunk);
    stream.push(chunk);
    if (!hasTitle) {
      hasTitle = true;
      keys = _.keys(chunk);
      fs.writeSync(fd, `${keys.map((o, i) => _.padEnd(o, widths[o] || widths[i] || 20)).join('')}\n`);
    }
    fs.write(fd, `${_.values(chunk).map((o, i) => _.padEnd(o, widths[keys[i]] || widths[i] || 20)).join('')}\n`, callback);
  };

  stream.on('finish', function () {
    fs.close(fd, ()=>{
      utils.debug('textWriter [finish]');
    });
  });

  return stream;
};